package com.hostmanagement.finance;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hostmanagement.user.UserBean;

public class AddFinanceServlet  extends HttpServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String TIMEOUT = "timeout";
	private String encoding = null;
	
	public void init() throws ServletException
	{
		
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		// user session check
		HttpSession session = req.getSession();
		UserBean userBean = (UserBean)session.getAttribute("userBean");
		
		// set URL encoding
		//req.setCharacterEncoding(encoding);
		
		List itemList = new ArrayList();
		float totalMoney = 0;
		
		String financeItemIds [] = req.getParameterValues("financeItemKey");
		for(int i=0;i<financeItemIds.length;i++){
			String itemId = financeItemIds[i];
			String itemvalue = req.getParameter("value"+itemId);
			
			if(itemvalue != null && !"".equals(itemvalue)){
				Map map = new HashMap();
				map.put("itemKey", itemId);
				map.put("itemValue", itemvalue);
				
				totalMoney += new Float(itemvalue.trim()).floatValue();
				
				itemList.add(map);
			}
		}
		
		int checkUser = userBean.getUserId();
		
		String monthTime = req.getParameter("monthTime");
//		String userId = req.getParameter("userId");
		String houseId = req.getParameter("houseId");
		
		
		FinanceManage financeManage = new FinanceManage();
		int key = financeManage.addFinance( new Integer(houseId.trim()).intValue(), totalMoney, monthTime, checkUser);

		
		for(int i=0;i<itemList.size();i++){
			Map map = (Map)itemList.get(i);
			String itemKey = (String)map.get("itemKey");
			String itemValue = (String)map.get("itemValue");
			
			financeManage.addUserFinanceItem(key, new Integer(itemKey.trim()).intValue(), 
					new Float(itemValue.trim()).floatValue());		
		}
		
		
		
	}
}
